/*
 * Copyright (c) 2011 Samuel Ventura All Rights Reserved
 */
package dev2net;

import opto22.snappac.comm.IpUtil;
import opto22.snappac.comm.PointInfo;

/**
 *
 * @author samuel
 */
public class MmpConfig {
    private String name;
    private String ip;
    private int port;
    private int index;
    private PointInfo pointInfo;
    private MmuConfig mmuConfig;
    private float read;
    private Float write;
    
    public MmpConfig(String config) {
        String[] parts = config.split(",");
        
        name  = parseName(parts[0]);
        ip  = parseIp(parts[1]);
        port  = parsePort(parts[2]);
        index  = parseIndex(parts[3]);
    }

    public int getModuleIndex() {
        return index / 4;
    }
    
    public int getPointIndex() {
        return index % 4;
    }
    
    public String getName() {
        return name;
    }
    
    public int getIndex() {
        return index;
    }

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

    public PointInfo getPointInfo() {
        return pointInfo;
    }

    public void setPointInfo(PointInfo pointInfo) {
        this.pointInfo = pointInfo;
    }

    public MmuConfig getMmuConfig() {
        return mmuConfig;
    }

    public void setMmuConfig(MmuConfig mmuConfig) {
        this.mmuConfig = mmuConfig;
    }

    private String parseName(String string) {
        return string;
    }

    private String parseIp(String string) {
        try {
            return IpUtil.stringIp4(IpUtil.parseIp4(string));
        } catch (RuntimeException ex) {
            throw new RuntimeException("Invalid ip format");
        }
    }

    private int parsePort(String string) {
        try {
            int v = Integer.parseInt(string);
            if (v<1 || v>65535) throw new RuntimeException("Invalid tcp port range");
            return v;
        } catch (NumberFormatException ex) {
            throw new RuntimeException("Invalid tcp port format");
        }
    }

    private int parseIndex(String string) {
        try {
            int v = Integer.parseInt(string);
            if (v<0 || v>63) throw new RuntimeException("Invalid index range");
            return v;
        } catch (NumberFormatException ex) {
            throw new RuntimeException("Invalid index format");
        }
    }

    public String unitString() {
        return String.format("%s:%d", ip, port);
    }

    //USER CONTROL
    public synchronized void write(float write) {
        this.write = write;
    }

    public float read() {
        return read;
    }

    //INTERNAL CONTROL
    public synchronized Float getWrite() {
        return write;
    }

    public synchronized void clearWrite() {
        write = null;
    }

    public void setRead(float read) {
        this.read = read;
    }
    
}
